package dijjer.io.xfer.http.handlers;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Map;
import dijjer.io.xfer.http.HTTPResponse;

public class TemplateResponse extends HTTPResponse {

	public static final String VERSION = "$Id: TemplateResponse.java 2 2008-03-21 14:33:03Z ian.clarke $";
	private final StringBuffer _response = new StringBuffer();
	private static final String TOKEN_INDICATOR = "@@";

	public TemplateResponse(String template, int code, String message, String contentType)
	{
		super(code, message, contentType);
		_response.append(template);
	}

	protected long getContentLength()
	{
		return _response.length();
	}

	protected void writeTo(OutputStream out) throws IOException
	{
		out.write(_response.toString().getBytes());
	}

	public void setPageField(String name, String value)
	{
		String pageField = TOKEN_INDICATOR + name.toUpperCase() + TOKEN_INDICATOR;
		int start = -1;
		while ((start =_response.indexOf(pageField)) >= 0) {
			_response.replace(start, start + pageField.length(), value);
		}

	}

	public void setPageFields(Map fields) {
		for (Iterator i = fields.keySet().iterator(); i.hasNext();) {
			String name = (String) i.next();
			setPageField(name, (String) fields.get(name));
		}
	}
}

